/*
  Copyright (c) 2009 Ullio
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

package ullio.mouse
{	
	import flash.display.DisplayObjectContainer;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;	
	import ullio.view.DebugConsole;
	
	/**
	 * Enables mouse tracking for a target - currently only for stage
	 */
	public class EnableMouseTracking
	{		
		
		public var xChangeBeforeSaving:Number = 150;
		public var yChangeBeforeSaving:Number = 150;		
		public var storeMouseMovement:Array;
						
		protected var _debugConsole:DebugConsole;		
		protected var _target:DisplayObjectContainer;
		protected var _application:DisplayObjectContainer;				
		protected var _debug:Boolean;
		
		/**
		 * Debug enables a view to watch mouse movements
		 */
		public function get debug():Boolean{
			return _debug;
		}
		public function set debug(value:Boolean):void{		
			_debug = value;
			if (value && _debugConsole == null)
				_debugConsole = new DebugConsole();
			
			handleDebugConsole();			
		}
		
		/**
		 * The container which will enable mouse tracking - currently only for stage
		 */
		public function get target():DisplayObjectContainer
		{
			return _target;
		}		
		public function set target(value:DisplayObjectContainer):void
		{
			if (value == _target)
				return;
			
			if (_target)
				cleanupTarget(_target);
					
			_target = value;
			initArrays();
			initTarget(_target);
			handleDebugConsole();
		}
		
		/**
		 * Reference to the application, needed to use debug console
		 */
		public function get application():DisplayObjectContainer
		{
			return _application;
		}		
		public function set application(value:DisplayObjectContainer):void
		{
			if (value != null){
				_application = value;
			}
		}
		/**
		 * Initialize data arrays
		 */				
		protected function initArrays():void{
			storeMouseMovement = new Array();
		}
		
		/**
		 * Set up event listeners	 
		 * @param target container
		 */
		protected function initTarget(target:DisplayObjectContainer):void
		{
			target.addEventListener(MouseEvent.CLICK, onMouseClick, true, 100, true);
			target.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, true, 100, true);
		}
		
		/**
		 * Remove all event listeners		 
		 * @param target container
		 */
		protected function cleanupTarget(target:DisplayObjectContainer):void
		{
			target.removeEventListener(MouseEvent.CLICK, onMouseClick, true);
			target.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, true);
		}		
				
		protected function onMouseMove(event:MouseEvent):void
		{
			var save:Boolean = checkLastValue(storeMouseMovement, [event.stageX, event.stageY]);			
			
			if (save){
				storeMouseMovement.push([event.stageX, event.stageY]);
				if (_debugConsole != null)
					_debugConsole.text += "stored position [" + event.stageX + "," + event.stageY + "]\n";				
			}						
		}
						
		private function checkLastValue(ar:Array, mouse:Array):Boolean{
			if (ar.length == 0)
				return true;
				
			var lastX:Number = storeMouseMovement[storeMouseMovement.length-1][0];
			var lastY:Number = storeMouseMovement[storeMouseMovement.length-1][1];		
			var xChange:Number = Math.abs(lastX - mouse[0]);
			var yChange:Number = Math.abs(lastY - mouse[1]);
			
			if (xChange >= xChangeBeforeSaving || yChange >= yChangeBeforeSaving)
				return true;
			
			return false;
		}		
		
		// currently not storing mouse clicks
		protected function onMouseClick(event:MouseEvent):void
		{
			if (event.ctrlKey)
				debug = !_debug;
			
			if (event.shiftKey){
				storeMouseMovement = [];
				if (_debugConsole != null)
					_debugConsole.text = '';
			}			
		}
		
		// hide or show the debug console
		private function handleDebugConsole():void{	
			if (_application != null){
				if (_application.contains(_debugConsole)){
					_application.removeChild(_debugConsole);
				}
				if (_debug){
					_application.addChild(_debugConsole);
				} 
			}
		}		
	}
}